use {
    super::{common::AppState, error_handle},
    axum::{
        extract::{self, Query, State},
        http::StatusCode,
        response::Json,
    },
    serde::{self, Deserialize},
    tron::{base, service},
};

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct BalanceCoinParams {
    account: String,
}

pub async fn balance_coin(
    State(state): State<AppState>,
    Query(params): Query<BalanceCoinParams>,
) -> Result<Json<u64>, (StatusCode, String)> {
    let client = base::client::build_client(state.env);
    let acct = params.account;
    let account = service::coin::get_account(&client, acct.as_str()).await
        .map_err(error_handle::internal_error)?;
    let balance = account.balance;

    Ok(Json::from(balance))
}

#[derive(serde::Deserialize)]
pub struct TransferCoinApiParams {
    from: String,
    from_pr: String,
    to: String,
    amount: u64,
}

pub async fn transfer_coin(
    State(state): State<AppState>,
    extract::Json(body): extract::Json<TransferCoinApiParams>,
) -> Result<Json<String>, (StatusCode, String)> {
    let client = base::client::build_client(state.env);
    let from = body.from;
    let pr = body.from_pr;
    let to = body.to;
    let amount = body.amount;
    let tx_hash =
        service::coin::transfer_coin(&client, pr.as_str(), from.as_str(), to.as_str(), amount).await
            .map_err(error_handle::internal_error)?;
    Ok(Json::from(tx_hash))
}
